#!/usr/bin/python

import socket,traceback
import os,time
import json
import threading
from Queue import Queue

from Dev_state import Dev


"""
host = ''
port = 50000
"""
host = ''
port = 50000
DATA ={}
class Json_sock(threading.Thread):
    def __init__(self,host,port):
        print "initializing ......network"
        try:
            self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            self.sock.bind((host,port))
            self.sock.listen(10)
        except socket.error, e:
            print "Network initialized ...faild:  %s" %e
        time.sleep(0.3)
        print "Network initialized ...ok\nThread initializing ..."
        time.sleep(0.3)
        threading.Thread.__init__(self)
        #self.Lock_stack = queue
        print "initializing ... ok"
        data  = Dev("Qingluan","off").getDeviceInformation()
        print "Data loading ...ok"
        self.json_data = self.encode_json(data)
        print self.json_data
        print "Data encoding ...ok"
        self.DATA = [data]
        os.system("clear")
        print "Listening..."
    def listenClient(self):
      while True:
          
          try:
              clientsock,clientaddr = self.sock.accept()
              time.sleep(0.3)
              print "Connected to client ...ok"
          except KeyboardInterrupt :
              raise
          except socket.error ,e:
              print "client connecting error : %s" %e
              #clientsock.timeout(10)
          try:
              if (clientsock):
                  print "Got connection from : " ,clientsock.getpeername()
              else:
                  continue
              while True:
                  response_to_client = self.json_data
                  if clientsock.getpeername():
                      print "send data to " ,clientsock.getpeername()
                      print response_to_client
                      response_to_client+= "\n"
                      clientsock.sendall(response_to_client)
                      print "send ...ok"
                  else :
                      continue
                 # print "get data ...", 
                  #Ensuredata = clientsock.recv(4096)
                  #if not len(Ensuredata):
                   #   print "first data ensure error"
                    #  continue
                  #print Ensuredata
                  #print "ok"
                  #Ensuredata  = self.parase_json(Ensuredata) ####this is a json
                 # print Ensuredata
                  #print "----"*8
                 # print "Keep conecting ...",clientsock.getpeername()#result_ensure = clientsock.recv(4096)
                 # if Ensuredata :
                 #     Lock_stack.put(child_thread)
                  #Lock_C.wait()
                  print "re-initializing ...",
                  try:
                      clientsock.close()
                  except KeyboardInterrupt:
                      pass
                  except :
                      traceback.print_exc()
                  if clientsock ==None:
                      print "ok"
                  else:
                      print "error\n"
          except (KeyboardInterrupt,SystemExit):
              raise
              
          except IOError:
              clientsock.close()
              print "Client disconnected"
              traceback.print_exc()
       
    def run(self):
        while True:
            self.listenClient()

    def talk_json(self,client):
        if client != None:
            temp = client.recv(4096)
            print "new:", temp
            return self.parase_json(temp)
        else :
            pass

    def parase_json(self,json_obj):
        obj = Json_decoder().decode(json_obj)
        return obj
    def encode_json(self,obj):
        json_obj = Json_encoder().encode(obj)
        return json_obj
           

class Json_encoder(json.JSONEncoder):
    def default(self,obj):
        d = {}
        d['__class__'] = obj.__class__.__name__
        d['__module__'] = obj.__module__
        d.update(obj.__dict__)
        return d

class Json_decoder(json.JSONDecoder):
    def __init__(self):
        json.JSONDecoder.__init__(self,object_hook=self.dict2object)
    def dict2object(self,d):
        if '__class__' in d:
            class_name = d.pop('__class__')
            module_name = d.pop('__module__')
            module = __import__(module_name)
            class_ = getattr(module,class_name)
            args = dict((key.encode('ascii') ,value) for key,value in d.items())
            inst = class_(**args)
        else:
            inst = d
        return inst



if __name__ =="__main__":
    customer = Json_sock(host,port)
    customer.run()
    """test_data = Dev("first","off").getDeviceInformation()
    p = Json_encoder().encode(test_data)
    print type(p),"||",p

    o = Json_decoder().decode(p)
    print type(o),"||",o
"""
